#include "board.h"
#include "fsl_elcdif.h"
#include "fsl_lpi2c.h"
#include "fsl_gpio.h"
#include "fsl_cache.h"
#include "ST1633E.h"
#include "fsl_debug_console.h"

/*******************************************************************************
 * Definitions
 ******************************************************************************/

/* Macros for the touch touch controller. */
#define TOUCH_I2C LPI2C1

/* Select USB1 PLL (480 MHz) as master lpi2c clock source */
#define TOUCH_LPI2C_CLOCK_SOURCE_SELECT (0U)
/* Clock divider for master lpi2c clock source */
#define TOUCH_LPI2C_CLOCK_SOURCE_DIVIDER (5U)

#define TOUCH_I2C_CLOCK_FREQ ((CLOCK_GetFreq(kCLOCK_Usb1PllClk) / 8) / (TOUCH_LPI2C_CLOCK_SOURCE_DIVIDER + 1U))
#define TOUCH_I2C_BAUDRATE   1000U
void InitTouch(void)
{
    lpi2c_master_config_t lpi2cConfig = {0};
    status_t status;
    
    uint16_t x;
    uint16_t y;
    gpio_pin_config_t resetPinConfig = {
        .direction = kGPIO_DigitalOutput, .outputLogic = 0, .interruptMode = kGPIO_NoIntmode};
    
    GPIO_PinInit(BOARD_TOUCH_RST_GPIO, BOARD_TOUCH_RST_PIN, &resetPinConfig);
    resetPinConfig.direction =  kGPIO_DigitalInput;
    resetPinConfig.outputLogic = 0;
       resetPinConfig.interruptMode =  kGPIO_IntFallingEdge;
    GPIO_PinInit(BOARD_TOUCH_INT_GPIO, BOARD_TOUCH_INT_PIN, &resetPinConfig);
    /*Clock setting for LPI2C*/
    CLOCK_SetMux(kCLOCK_Lpi2cMux, TOUCH_LPI2C_CLOCK_SOURCE_SELECT);
    CLOCK_SetDiv(kCLOCK_Lpi2cDiv, TOUCH_LPI2C_CLOCK_SOURCE_DIVIDER);
              
    LPI2C_MasterGetDefaultConfig(&lpi2cConfig);
    lpi2cConfig.baudRate_Hz = 1000000;
    LPI2C_MasterInit(LPI2C1, &lpi2cConfig, TOUCH_I2C_CLOCK_FREQ);

    GPIO_PinWrite(BOARD_TOUCH_RST_GPIO, BOARD_TOUCH_RST_PIN, 0);
    SDK_DelayAtLeastUs(65000, SDK_DEVICE_MAXIMUM_CPU_CLOCK_FREQUENCY);
    GPIO_PinWrite(BOARD_TOUCH_RST_GPIO, BOARD_TOUCH_RST_PIN, 1);

}

void get_touch_point(touch_point_t* touch_point)
{
    uint8_t rxbuff[3] = {};
    BOARD_Touch_I2C_Receive(0x70,0x12,1,(uint8_t*)&rxbuff,3);
    //SDK_DelayAtLeastUs(100, SDK_DEVICE_MAXIMUM_CPU_CLOCK_FREQUENCY);
    
    touch_point->x = rxbuff[1];
    touch_point->x = ((rxbuff[0]&0x70)<<4)+rxbuff[1];
    touch_point->x = touch_point->x;
        
    touch_point->y = rxbuff[2];
    touch_point->y = ((rxbuff[0]&0x07)<<8)+rxbuff[2];
    touch_point->y = touch_point->y;
    if(rxbuff[0]&0x80)
    {
        touch_point->touch_status = true;
    }else{
        touch_point->touch_status = false;
    }
}